from flask import Flask, jsonify, request
from flask_cors import CORS
import ddddocr
import requests
import base64
import os
import sys

current_directory = os.path.dirname(os.path.abspath(__file__))

# 跨域
app = Flask(__name__)
cors = CORS(app, supports_credentials=True)
static_path = './static'

def req_img(url):
    payload = {}
    headers = {}
    try:
        response = requests.request("GET", url, headers=headers, data=payload)
        return response.content
    except:
        return False


@app.route("/", methods=["POST"])
def hello():
    if request.method == 'POST':
        src = request.json.get('src')
        # 存图片
        if 'base64' in src:
            img_base64_decode = src.split(",")[1]
            img_base64_decode = base64.b64decode(img_base64_decode)
            with open(f'{static_path}/code.png', 'wb+') as f:
                f.write(img_base64_decode)
        else:
            content = req_img(src)
            if content:
                with open(f'{static_path}/code.png', 'wb+') as f:
                    f.write(content)
        # 读图识别
        with open(f'{static_path}/code.png', 'rb') as f:
            img_bytes = f.read()
            ocr = ddddocr.DdddOcr()
            res = ocr.classification(img_bytes)
            print(f'识别代码为:{res}')
            return res
    return ''




if __name__ == '__main__':
    app.run(host='0.0.0.0',port='9911', threaded=True, debug=True)
